import React from 'react'
import { SchemaForm, Item, Submit, Reset, Observer, Layout } from '@amazebird/antd-schema-form'
import type { SchemaType } from '@amazebird/antd-schema-form'
import { areaData } from '../data'

async function getAreaData(data: any, path?: any) {
  if (!path) return data
  const result = path.reduce((target, id) => {
    const temp = target.find((item) => item.id === id)
    return temp.children
  }, data)
  return result
}

const schema: SchemaType = {
  province: {
    label: '省',
    component: 'Select',
    options: async () => {
      const prvinceArr = await getAreaData(areaData)
      return prvinceArr.map(({ id, name }) => ({ label: name, value: id }))
    },
    required: [true, '请选择省']
  },
  city: {
    label: '市',
    component: 'Select',
    options: Observer({
      watch: 'province',
      action: async (province) => {
        if (!province) return []
        const cityArr = await getAreaData(areaData, [province])
        return cityArr.map(({ id, name }) => ({ label: name, value: id }))
      }
    }),
    value: Observer({
      watch: 'province',
      action: () => {
        return null
      }
    }),
    required: [true, '请选择市']
  },
  area: {
    label: '县/区',
    component: 'Select',
    observer: {
      watch: 'city',
      action: async (city, { formData }) => {
        if (!city) {
          return {
            options: [],
            value: null
          }
        } else {
          const { province } = formData
          const areaArr = await getAreaData(areaData, [province, city])
          const options = areaArr.map(({ id, name }) => ({ label: name, value: id }))
          return {
            options,
            value: null
          }
        }
      }
    },
    required: [true, '请选择区']
  }
}

function BaseDemo() {
  return (
    <SchemaForm schema={schema}>
      <Item field="province" />
      <Item field="city" />
      <Item field="area" />

      <Layout align="left" offset={8}>
        <Submit onFinish={(data) => { console.info(data) }} />
        <Reset />
      </Layout>

    </SchemaForm>
  )
}

export default BaseDemo
